package internal

import (
	"GameServer/Game/dbmodule"
	"GameServer/Game/m"
	"sync"
)

// 活跃玩家
type ActiveUser struct {
	OnLine  map[string]*AUser // 在线
	OffLine map[string]*AUser // 离线
	rw      sync.RWMutex
}

type AUser struct {
	Uid          string
	LockBlockTid int64 // 当前关
	OffLineTime  int64 // 离线时间
}

func NewActiveUser() *ActiveUser {
	return &ActiveUser{}
}

func (ea *ActiveUser) Init() {
	ea.OnLine = make(map[string]*AUser)
	ea.OffLine = make(map[string]*AUser)

	users := make([]*m.User, 0)
	err := dbmodule.MgoDB.GameDB.FindAll("user", nil, nil, &users)
	if err != nil {
		return
	}

	for _, item := range users {
		uid := item.Uid.Hex()
		ea.OffLine[uid] = &AUser{
			Uid:          uid,
			LockBlockTid: item.Pos.LockBlockTid,
			OffLineTime:  item.OfflineTime,
		}
	}
}

func (ea *ActiveUser) Run(closeSig chan bool) {

}

func (ea *ActiveUser) Destroy() {

}

// 玩家上线
func (ea *ActiveUser) UserOnLine(u *m.User) {
	ea.rw.Lock()
	defer ea.rw.Unlock()

	uid := u.Uid.Hex()
	ea.OnLine[uid] = &AUser{
		Uid:          uid,
		LockBlockTid: u.Pos.LockBlockTid,
		OffLineTime:  u.OfflineTime,
	}
	delete(ea.OffLine, uid)
}

// 玩家离线
func (ea *ActiveUser) UserOffLine(u *m.User) {
	ea.rw.Lock()
	defer ea.rw.Unlock()

	uid := u.Uid.Hex()
	ea.OffLine[uid] = &AUser{
		Uid:          uid,
		LockBlockTid: u.Pos.LockBlockTid,
		OffLineTime:  u.OfflineTime,
	}
	delete(ea.OnLine, uid)
}

func (ea *ActiveUser) RecomFriend(u *m.User) (r []string) {
	r = make([]string, 0)
	cnt := 0
	ea.rw.RLock()
	defer ea.rw.RUnlock()

	for _, val := range ea.OnLine {
		// 匹配三章以内的玩家
		if u.Pos.LockBlockTid-21 <= val.LockBlockTid && val.LockBlockTid <= u.Pos.LockBlockTid+21 {
			cnt++
			r = append(r, val.Uid)
		}
		if cnt > 30 {
			return
		}
	}

	uidLst := make([]string, 0)
	for _, val := range ea.OffLine {
		if val.OffLineTime >= 86400 { //离线超过24小时，删除匹配池
			uidLst = append(uidLst, val.Uid)
			continue
		}
		// 匹配三章以内的玩家
		if u.Pos.LockBlockTid-21 <= val.LockBlockTid && val.LockBlockTid <= u.Pos.LockBlockTid+21 {
			cnt++
			r = append(r, val.Uid)
		}
		if cnt > 30 {
			return
		}
	}

	// 离线的玩家，踢出离线匹配池
	for _, item := range uidLst {
		delete(ea.OffLine, item)
	}
	return
}
